{{/* Masonry Gallery 短代码*/}}
{{- $columns := .Get "columns" | default 3 -}}
{{- $gutter := .Get "gutter" | default 20 -}}
{{- $animate := .Get "animate" | default "true" -}}
{{- $useTransform := .Get "useTransform" | default "true" -}}
{{- $center := .Get "center" | default "true" -}}
{{- $maxColumns := .Get "maxColumns" | default 5 -}}

{{- if not (.Page.Scratch.Get "masonryCounter") -}}
  {{- .Page.Scratch.Set "masonryCounter" 0 -}}
{{- end -}}
{{- .Page.Scratch.Add "masonryCounter" 1 -}}
{{- $counter := .Page.Scratch.Get "masonryCounter" -}}
{{- $pageId := .Page.File.UniqueID | default (.Page.RelPermalink | md5 | truncate 8 "") -}}
{{- $uniqueId := printf "masonry-%s-%d" $pageId $counter -}}

{{/* 检查是否启用灯箱功能 */}}
{{- $globalLightbox := site.Params.lightbox | default dict -}}
{{- $pageLightbox := .Page.Params.lightbox | default dict -}}
{{- $lightboxEnabled := cond (isset $pageLightbox "enabled") $pageLightbox.enabled ($globalLightbox.enabled | default false) -}}

{{/* 内联样式 */}}
<style>
/* {{ $uniqueId }} 专用样式 */
#{{ $uniqueId }} {
  width: 100%;
}

#{{ $uniqueId }} .masonry-container {
  width: 100%;
  position: relative;
}

#{{ $uniqueId }} .masonry-item {
  display: inline-block;
  width: 100%;
  margin-bottom: {{ $gutter }}px;
  break-inside: avoid;
  box-sizing: border-box;
}

#{{ $uniqueId }} .masonry-item img {
  width: 100%;
  height: auto;
  display: block;
  transition: transform 0.3s ease-in-out;
  border-radius: 0.5rem;
}

#{{ $uniqueId }} .glightbox {
  display: block;
  text-decoration: none;
  overflow: hidden;
  cursor: pointer;
  border-radius: 0.5rem;
}

#{{ $uniqueId }} .glightbox:hover,
#{{ $uniqueId }} .glightbox:focus {
  text-decoration: none;
  outline: none;
}

#{{ $uniqueId }} .masonry-item:hover img {
  transform: scale(1.05);
}

#{{ $uniqueId }} .masonry-item {
  overflow: hidden;
  border-radius: 0.5rem;
}
</style>

<div class="masonry-gallery" 
     id="{{ $uniqueId }}"
     data-columns="{{ $columns }}"
     data-gutter="{{ $gutter }}"
     data-animate="{{ $animate }}"
     data-use-transform="{{ $useTransform }}"
     data-center="{{ $center }}"
     data-max-columns="{{ $maxColumns }}"
     data-lightbox="{{ $lightboxEnabled }}">

  <div class="masonry-container">
    {{/* 解析原始markdown中的图片语法 */}}
    {{- $images := findRE `!\[([^\]]*)\]\(([^)]+)(?:\s+"([^"]*)")?\)` .Inner -}}

    {{- range $index, $imgMarkdown := $images -}}
      {{- $alt := replaceRE `!\[([^\]]*)\].*` "$1" $imgMarkdown -}}
      {{- $src := replaceRE `!\[[^\]]*\]\(([^)]+?)(?:\s+.*)?(?:\)|$)` "$1" $imgMarkdown -}}
      {{- $title := "" -}}
      {{- if findRE `!\[[^\]]*\]\([^)]*\s+"[^"]*"\)` $imgMarkdown -}}
        {{- $title = replaceRE `!\[[^\]]*\]\([^)]*\s+"([^"]*)"\)` "$1" $imgMarkdown -}}
      {{- end -}}

      {{/* 使用image-processor处理图片路径 */}}
      {{- partial "content/image-processor.html" (dict
        "context" $.Page
        "src" $src
        "alt" $alt
        "caption" $title
        "enableResponsive" true
        "enablePlaceholder" false
        "outputType" "data"
      ) -}}

      {{/* 获取处理结果 */}}
      {{- $finalUrl := $.Page.Scratch.Get "imageUrl" -}}

      <div class="masonry-item">
        {{- if $lightboxEnabled -}}
          <a href="{{ $finalUrl }}" 
             class="glightbox"
             data-gallery="{{ $uniqueId }}"
             {{- if or $title $alt -}}
             data-description="
             {{- if $title -}}<h4>{{ $title }}</h4>{{- end -}}
             {{- if and $alt (ne $alt $title) -}}<p>{{ $alt }}</p>{{- end -}}
             "
             {{- end -}}>
            
            {{/* 使用image-processor生成图片HTML */}}
            {{- partial "content/image-processor.html" (dict
              "context" $.Page
              "src" $src
              "alt" $alt
              "caption" $title
              "enableResponsive" true
              "enablePlaceholder" false
              "outputType" "img"
            ) -}}
          </a>
        {{- else -}}
          {{/* 不使用灯箱时直接生成图片 */}}
          {{- partial "content/image-processor.html" (dict
            "context" $.Page
            "src" $src
            "alt" $alt
            "caption" $title
            "enableResponsive" true
            "enablePlaceholder" false
            "outputType" "img"
          ) -}}
        {{- end -}}
      </div>
    {{- end -}}
  </div>
</div>

{{/* 内联初始化脚本 */}}
<script>
(function() {
  const containerId = '{{ $uniqueId }}';
  const config = {
    columns: {{ $columns }},
    gutter: {{ $gutter }},
    maxColumns: {{ $maxColumns }},
    lightbox: {{ $lightboxEnabled }},
    animate: {{ $animate }},
    useTransform: {{ $useTransform }},
    center: {{ $center }}
  };
  
  console.log('Initializing masonry gallery:', containerId, config);
  
  function initMasonryGallery() {
    const container = document.getElementById(containerId);
    if (!container) {
      console.error('Masonry container not found:', containerId);
      return;
    }
    
    const masonryContainer = container.querySelector('.masonry-container');
    if (!masonryContainer) {
      console.error('Masonry inner container not found');
      return;
    }
    
    // 检查库是否加载
    if (typeof Macy === 'undefined') {
      console.error('Macy.js not loaded');
      return;
    }
    
    console.log('Found container and Macy, initializing...');
    
    // 初始化 Macy.js
    try {
      const macyInstance = Macy({
        container: masonryContainer,
        trueOrder: false,
        waitForImages: true,
        useOwnImageLoader: false,
        debug: false,
        mobileFirst: true,
        columns: config.columns,
        margin: {
          x: config.gutter,
          y: config.gutter
        },
        breakAt: {
          1400: Math.min(config.maxColumns, config.columns),
          1200: Math.min(config.maxColumns, config.columns),
          940: Math.min(config.maxColumns, config.columns),  // 修复
          768: Math.min(3, config.columns),
          520: Math.min(2, config.columns),
          400: 1
        }
      });
      
      console.log('Macy initialized successfully for', containerId);
      
      // 等待图片加载完成再重新计算
      const images = masonryContainer.querySelectorAll('img');
      let loadedImages = 0;
      const totalImages = images.length;
      
      function onImageLoad() {
        loadedImages++;
        console.log(`Image ${loadedImages}/${totalImages} loaded`);
        
        if (loadedImages === totalImages) {
          setTimeout(() => {
            if (macyInstance && macyInstance.reCalculate) {
              macyInstance.reCalculate(true);
              console.log('Macy layout recalculated after all images loaded');
            }
          }, 100);
        }
      }
      
      images.forEach(img => {
        if (img.complete) {
          onImageLoad();
        } else {
          img.addEventListener('load', onImageLoad);
          img.addEventListener('error', onImageLoad);
        }
      });
      
    } catch (error) {
      console.error('Error initializing Macy:', error);
    }
    
    // 初始化 GLightbox
    if (config.lightbox) {
      if (typeof GLightbox !== 'undefined') {
        try {
          // 获取全局lightbox配置
          let globalLightboxConfig = window.HUGO_GALLERY_CONFIG?.lightbox_options || {};
          
          if (typeof globalLightboxConfig === 'string') {
            try {
              globalLightboxConfig = JSON.parse(globalLightboxConfig);
            } catch (e) {
              console.error('Error parsing masonry GLightbox config:', e);
              globalLightboxConfig = {};
            }
          }          
          const lightbox = GLightbox({
            selector: `#${containerId} .glightbox`,
            touchNavigation: globalLightboxConfig.touchnavigation ?? globalLightboxConfig.touchNavigation ?? true,
            loop: globalLightboxConfig.loop ?? true,
            draggable: globalLightboxConfig.draggable ?? true,
            zoomable: globalLightboxConfig.zoomable ?? true,
            preload: globalLightboxConfig.preload ?? true,
            width: globalLightboxConfig.width || '90vw',
            height: globalLightboxConfig.height || '90vh',
            descPosition: globalLightboxConfig.descposition || globalLightboxConfig.descPosition || 'bottom',
            onOpen: () => {
              console.log('GLightbox opened for', containerId);
            }
          });
          
          console.log('GLightbox initialized successfully for', containerId, 'with global config');
          
        } catch (error) {
          console.error('Error initializing GLightbox:', error);
        }
      } else {
        console.error('GLightbox not loaded but lightbox is enabled');
      }
    }
  }
  
  // 等待库加载完成
  function waitForLibraries() {
    let attempts = 0;
    const maxAttempts = 50;
    
    function check() {
      attempts++;
      
      const macyReady = typeof Macy !== 'undefined';
      const lightboxReady = !config.lightbox || typeof GLightbox !== 'undefined';
      
      if (macyReady && lightboxReady) {
        initMasonryGallery();
      } else if (attempts < maxAttempts) {
        setTimeout(check, 100);
      } else {
        console.error('Timeout waiting for libraries. Macy:', macyReady, 'GLightbox:', lightboxReady);
      }
    }
    
    check();
  }
  
  // 执行初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', waitForLibraries);
  } else {
    setTimeout(waitForLibraries, 50);
  }
})();
</script>